package com.smh.filter;

import com.alibaba.fastjson.JSONObject;
import com.smh.common.CommonResult;
import com.smh.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//导入的是javax.servlet下的Filter

@Slf4j
@WebFilter(urlPatterns = "/*")//拦截所有
//还需要加一个注解在启动类上
public class LoginFilter implements Filter {

    //初始化方法(有默认实现)只调用一次
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        System.out.println("init");

    }

    @Override//调用多次,每次拦截执行
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //先强转一下(本身就是HttpServlet类型)
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        //解决跨域问题
        res.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有域访问，或者指定允许的域
        res.setHeader("Access-Control-Allow-Methods", "*"); // 允许的 HTTP 方法
        res.setHeader("Access-Control-Max-Age", "3600"); // 预检请求的缓存时间（秒）
        res.setHeader("Access-Control-Allow-Headers", "*"); // 允许的 HTTP 头


        //放行之前的逻辑
        //获取url
        String url = req.getRequestURL().toString();
//        log.info(url);
        //如果是登录操作,放行
        if (url.contains("login")) {
            log.info("登录操作放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //log.info(req.toString());
        String jwt = req.getHeader("token");
        log.info(jwt);
        //判断是否有令牌
        if (!StringUtils.hasLength(jwt)) {
            log.info("请求头不存在token");
            CommonResult<String> cr = new CommonResult<>();
            cr.setCode(-1);
            cr.setMsg("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(cr);
            //响应数据给浏览器
            res.getWriter().write(jsonString);
            log.info("响应未登录数据");
            return;
        }

        try {
            JwtUtil.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败,返回错误信息");
            CommonResult<String> cr = new CommonResult<>();
            cr.setCode(-1);
            cr.setMsg("NOT_LOGIN");
            cr.setData(null);
            String jsonString = JSONObject.toJSONString(cr);
            //响应数据给浏览器
            res.getWriter().write(jsonString);
            return;
        }
        log.info("令牌合法,放行");
        //只是拦截了,你还需要放行啊
        filterChain.doFilter(servletRequest, servletResponse);

        //方形之后的逻辑
    }

    //销毁方法(有默认实现)只调用一次,服务停止时执行
    @Override
    public void destroy() {
        Filter.super.destroy();
        System.out.println("destroy");
    }
}
